/*
 * @lc app=leetcode.cn id=654 lang=java
 *
 * [654] 最大二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
   
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return dfs(nums, 0, nums.length);

    }
    public TreeNode dfs(int[] nums,int left,int right){
        if(right-left<1){
            return null;
        }
        if(right-left==1){
            return new TreeNode(nums[left]);
        }
        int max=Integer.MIN_VALUE;
        int maxIndex=-1;
        for(int i=left;i<right;i++){//找到根节点
            if(nums[i]>max){
                max=nums[i];
                maxIndex=i;
            }
        }
        TreeNode root=new TreeNode(max);
        root.left=dfs(nums, left, maxIndex);//构建左子树
        root.right=dfs(nums, maxIndex+1, right);//构建右子树
        return root;
    }
}
// @lc code=end

